package org.lanyu.springainovel.common.config;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.lanyu.springainovel.common.service.UserService;
import org.lanyu.springainovel.common.util.JwtTokenUtil;
import org.lanyu.springainovel.common.dto.CustomUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * JWT认证过滤器
 * 拦截每个请求并验证JWT令牌
 * 不再维护单独的排除路径列表，由SecurityConfig统一管理
 */
@Slf4j
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    /**
     * 判断是否应该跳过过滤
     * 对于登录和注册接口，跳过JWT验证
     * /auth/me接口需要进行JWT验证
     */
    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        String path = request.getRequestURI();
        return path.equals("/auth/login") || path.equals("/auth/register");
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        String username = null;
        String jwtToken = null;
        try {
            
            // 获取Authorization头
            String authorizationHeader = request.getHeader("Authorization");

            // 提取JWT令牌
            if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
                jwtToken = authorizationHeader.substring(7);
                username = jwtTokenUtil.getUsernameFromToken(jwtToken);
            }

            // 验证令牌并设置认证信息
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                UserDetails userDetails = userService.loadUserByUsername(username);

                if (jwtTokenUtil.validateToken(jwtToken, userDetails)) {
                    // 尝试从令牌中获取用户ID和昵称
                    Long userId = jwtTokenUtil.getUserIdFromToken(jwtToken);
                    String nickname = jwtTokenUtil.getNicknameFromToken(jwtToken);
                    // 创建自定义的认证对象
                    UsernamePasswordAuthenticationToken authenticationToken = getUsernamePasswordAuthenticationToken(userDetails, userId, nickname);
                    authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                } else {
                    System.out.println("JWT令牌验证失败");
                }
            }
        } catch (Exception e) {
            log.error("JWT令牌验证失败: {}", e.getMessage());
            e.printStackTrace();
            log.debug("JWT Token: {}", jwtToken);
            log.debug("Username: {}", username);
        }
        // 无论JWT验证是否成功，都继续执行过滤器链
        // 对于需要认证的请求，如果没有有效的认证信息，Spring Security会拒绝访问
        filterChain.doFilter(request, response);
    }

    private static @NotNull UsernamePasswordAuthenticationToken getUsernamePasswordAuthenticationToken(UserDetails userDetails, Long userId, String nickname) {
        CustomUserDetails customUserDetails;
        if (userDetails instanceof CustomUserDetails) {
            customUserDetails = (CustomUserDetails) userDetails;
            // 如果令牌中有用户ID和昵称，更新到用户详情中
            if (userId != null) {
                customUserDetails.setUserId(userId);
            }
            if (nickname != null) {
                customUserDetails.setNickname(nickname);
            }
        } else {
            // 如果不是自定义用户详情，创建一个新的
            customUserDetails = new CustomUserDetails(
                    userDetails.getUsername(),
                    userDetails.getPassword(),
                    true, 
                    true, 
                    true, 
                    true, 
                    userDetails.getAuthorities(),
                    userId != null ? userId : 0L,
                    nickname != null ? nickname : ""
            );
        }

        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(customUserDetails, null, customUserDetails.getAuthorities());
        return authenticationToken;
    }
}
